package com.pks.datacenter.listener;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.annotation.WebListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import com.pks.datacenter.common.Configuration;
import com.pks.datacenter.config.MyConfig;
import com.pks.datacenter.entity.basic.JobInfo;
import com.pks.datacenter.entity.basic.SystemConfig;
import com.pks.datacenter.job.QuartzJob;
import com.pks.datacenter.service.basic.JobInfoService;
import com.pks.datacenter.service.basic.SystemConfigService;
import com.pks.datacenter.utils.QuartzManager;
import com.pks.web.listener.BaseApplicationListener;

@SuppressWarnings("all")
@WebListener
public class ApplicationListener extends BaseApplicationListener {
	
	private Logger logger = LoggerFactory.getLogger(ApplicationListener.class);

	private SystemConfigService systemConfigService = null;
	//版本号
	private Integer version = 0;

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		super.contextInitialized(sce);
		systemConfigService = wac.getBean(SystemConfigService.class);
		initVersion();
		initConfigMap();
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		super.contextDestroyed(sce);
		if(!Configuration.executorService.isShutdown()){
			Configuration.executorService.shutdown();
		}
	}

	private void initVersion() {
		// 判断数据库连接是否正常
		if (!databaseOk()) {
			return;
		}
		// 如果没有表，则从第一个SQL文件开始执行；如果执行失败了，则退出
		if (!existTable("t_systemconfig") && !exeSql("sql/init.sql")) {
			return;
		}
		// 如果没有版本记录，则插入版本记录
		List<SystemConfig> configList = systemConfigService.find(null,
				systemConfigService.initQbuilder("type", SystemConfig.KEY_SYSTEM_VERSION), 1);
		if (configList == null || configList.size() == 0) {
			updateDbVersion(0);
		} else {
			this.version = Integer.valueOf(configList.get(0).getVals());
		}
		if (this.version <1 && exeSql("sql/v01_20230531.sql")) {
			updateDbVersion(1);
		}
		
	}
	
	private String readFile(String path){
		try {
			Resource resource = new ClassPathResource(path);
			InputStream is = resource.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
	        String data = null;
	        StringBuffer sb = new StringBuffer();
	        while((data = br.readLine()) != null) {
	        	sb.append(data + "\r\n");
	        }
	        isr.close();
	        is.close();
	        br.close();
	        return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private void updateDbVersion(Integer version) {
		systemConfigService.update(SystemConfig.KEY_SYSTEM_VERSION, String.valueOf(version));
		this.version = version;
	}

	private void initConfigMap() {
		logger.error("4----:" + systemConfigService.getTotalRows(null));
//		MyConfig.getConfigMap().putAll(systemConfigService.findMap());
	}

}